package cn.edu.swu.miniwebsvr.core;

import java.io.InputStream;
import java.io.IOException;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;

public class HttpParser {

    public static Parameter parse(InputStream inputStream) throws IOException {
        Parameter parameter = new Parameter();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
        // TODO: [学号/姓名]
        // 1. 读取并解析 HTTP 请求行 (e.g., GET /path?param=value HTTP/1.1)
        //    - 设置 parameter.setMethod()
        //    - 设置 parameter.setUrl()，并解析出 URL 参数 (e.g., ?param=value)，存入 parameter.urlParams
        String requestLine = reader.readLine();
        if (requestLine == null || requestLine.isEmpty()) {
            throw new IOException("Empty request");
        }

        String[] requestParts = requestLine.split(" ");
        if (requestParts.length < 2) {
            throw new IOException("Invalid request line: " + requestLine);
        }

        String method = requestParts[0];
        String urlWithParams = requestParts[1];

        parameter.setMethod(method);

        String url;
        String queryString = "";
        int questionMarkIndex = urlWithParams.indexOf('?');
        if (questionMarkIndex != -1) {
            url = urlWithParams.substring(0, questionMarkIndex);
            queryString = urlWithParams.substring(questionMarkIndex + 1);
        } else {
            url = urlWithParams;
        }
        parameter.setUrl(url);

        if (!queryString.isEmpty()) {
            parseParams(queryString, parameter.getUrlParams());
        }
        parameter.setMethod(method);

        // 2. 循环读取并解析所有 HTTP 请求头 (e.g., Host: localhost:8080)
        //    - 存入 parameter.headers
        String headerLine;
        int contentLength = 0;
        while ((headerLine = reader.readLine()) != null) {
            if (headerLine.isEmpty()) {
                break;
            }

            int colonIndex = headerLine.indexOf(':');
            if (colonIndex > 0) {
                String headerName = headerLine.substring(0, colonIndex).trim();
                String headerValue = headerLine.substring(colonIndex + 1).trim();
                parameter.addHeader(headerName, headerValue);

                if ("Content-Length".equalsIgnoreCase(headerName)) {
                    contentLength = Integer.parseInt(headerValue);
                }
            }
        }

        // 3. 根据请求方法 (Method) 和请求头 (Content-Length, Content-Type) 判断并读取请求体
        //    - 适用于 POST 请求，解析请求体中的参数，存入 parameter.bodyParams
        if ("POST".equalsIgnoreCase(method) && contentLength > 0) {
            char[] bodyChars = new char[contentLength];
            int bytesRead = reader.read(bodyChars, 0, contentLength);
            if (bytesRead > 0) {
                String body = new String(bodyChars, 0, bytesRead);
                String contentType = parameter.getHeaders().get("Content-Type");
                if (contentType != null && contentType.contains("application/x-www-form-urlencoded")) {
                    parseParams(body, parameter.getBodyParams());
                }
            }
        }

        return parameter;
    }

    private static void parseParams(String paramString, Map<String, String> params) {
        if (paramString == null || paramString.isEmpty()) {
            return;
        }

        String[] pairs = paramString.split("&");
        for (String pair : pairs) {
            int equalsIndex = pair.indexOf('=');
            if (equalsIndex > 0) {
                try {
                    String key = URLDecoder.decode(pair.substring(0, equalsIndex), StandardCharsets.UTF_8.name());
                    String value = URLDecoder.decode(pair.substring(equalsIndex + 1), StandardCharsets.UTF_8.name());
                    params.put(key, value);
                } catch (Exception e) {
                    // 忽略解码错误
                }
            }
        }
    }
}